package com.zhuiyun.project.api.system.role.service.impl;

import com.zhuiyun.project.api.system.role.entity.TenantRole;
import com.zhuiyun.project.api.system.role.mapper.SysRoleMapper;
import com.zhuiyun.project.api.system.role.service.SysRoleService;
import com.zhuiyun.project.api.system.rolemenu.entity.TenantRoleMenu;
import com.zhuiyun.project.api.system.rolemenu.mapper.SysRoleMenuMapper;
import com.zhuiyun.project.api.system.user.entity.TenantUser;
import com.zhuiyun.project.api.system.user.entity.SysUserRole;
import com.zhuiyun.project.api.system.user.mapper.SysUserRoleMapper;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.exception.ServiceException;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.SecurityUtils;
import com.zhuiyun.project.utils.SpringUtils;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl implements SysRoleService
{
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;


    /**
    * @Author hbx
    * @Description 根据条件分页查询角色数据
    * @Date 2023/6/22 10:15
    * @param pageRequest
    * @param tenantRole
    */
    @Override
    public PageResult selectRoleList(PageRequest pageRequest, TenantRole tenantRole) {
        MybatisPageHelper.startPage(pageRequest);
        List<TenantRole> tenantRoleList =  roleMapper.selectRoleList(tenantRole);
        PageResult pageResult =MybatisPageHelper.getPageResult(tenantRoleList);
        return pageResult;
    }

    public List<TenantRole> selectRoleLists(TenantRole role)
    {
        return roleMapper.selectRoleList(role);
    }

    /**
    * @Author hbx
    * @Description 根据用户ID查询角色
    * @Date 2023/6/22 10:15
    * @param userId
    */
    @Override
    public List<TenantRole> selectRolesByUserId(Long userId)
    {
        List<TenantRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<TenantRole> roles = selectRoleAll();
        for (TenantRole role : roles)
        {
            for (TenantRole userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
    * @Author hbx
    * @Description 根据用户ID查询权限
    * @Date 2023/6/22 10:16
    * @param userId
    */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<TenantRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (TenantRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
    * @Author hbx
    * @Description 查询所有角色
    * @Date 2023/6/22 10:16

    */
    @Override
    public List<TenantRole> selectRoleAll()
    {
        return SpringUtils.getAopProxy(this).selectRoleLists(new TenantRole());
    }

    /**
    * @Author hbx
    * @Description 根据用户ID获取角色选择框列表
    * @Date 2023/6/22 10:17
    * @param userId
    */
    @Override
    public List<Long> selectRoleListByUserId(Long userId)
    {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
    * @Author hbx
    * @Description 通过角色ID查询角色
    * @Date 2023/6/22 10:17
    * @param roleId
    */
    @Override
    public TenantRole selectRoleById(Long roleId)
    {
        return roleMapper.selectRoleById(roleId);
    }

    /**
    * @Author hbx
    * @Description 校验角色名称是否唯一
    * @Date 2023/6/22 10:17
    * @param role
    */
    @Override
    public boolean checkRoleNameUnique(TenantRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        TenantRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
    * @Author hbx
    * @Description 校验角色权限是否唯一
    * @Date 2023/6/22 10:17
    * @param role
    */
    @Override
    public boolean checkRoleKeyUnique(TenantRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        TenantRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
    * @Author hbx
    * @Description 校验角色是否允许操作
    * @Date 2023/6/22 10:17
    * @param role
    */
    @Override
    public void checkRoleAllowed(TenantRole role)
    {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
    * @Author hbx
    * @Description 校验角色是否有数据权限
    * @Date 2023/6/22 10:18
    * @param roleId
    */
    @Override
    public void checkRoleDataScope(Long roleId)
    {
        if (!TenantUser.isAdmin(SecurityUtils.getUserId()))
        {
            TenantRole role = new TenantRole();
            role.setRoleId(roleId);
            PageRequest pageRequest = new PageRequest();
            List<TenantRole> roles = (List<TenantRole>) SpringUtils.getAopProxy(this).selectRoleList(pageRequest,role);
            if (StringUtils.isEmpty(roles))
            {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }




    /**
    * @Author hbx
    * @Description 新增保存角色信息
    * @Date 2023/6/22 10:18
    * @param role
    */
    @Override
    @Transactional
    public int insertRole(TenantRole role)
    {
        role.setDelFlag("0");
        // 新增角色信息
        roleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    /**
    * @Author hbx
    * @Description 修改保存角色信息
    * @Date 2023/6/22 10:18
    * @param role
    */
    @Override
    @Transactional
    public int updateRole(TenantRole role)
    {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        return insertRoleMenu(role);
    }


    /**
    * @Author hbx
    * @Description 修改角色状态
    * @Date 2023/6/22 10:18
    * @param role
    */
    @Override
    public int updateRoleStatus(TenantRole role)
    {
        return roleMapper.updateRole(role);
    }

    /**
    * @Author hbx
    * @Description 新增角色菜单信息
    * @Date 2023/6/22 10:18
    * @param role
    */
    private int insertRoleMenu(TenantRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<TenantRoleMenu> list = new ArrayList<TenantRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            TenantRoleMenu rm = new TenantRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
    * @Author hbx
    * @Description 通过角色ID删除角色
    * @Date 2023/6/22 10:18
    * @param roleId
    */
    @Override
    @Transactional
    public int deleteRoleById(Long roleId)
    {
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
        return roleMapper.deleteRoleById(roleId);
    }

    /**
    * @Author hbx
    * @Description 批量删除角色信息
    * @Date 2023/6/22 10:18
    * @param roleIds
    */
    @Override
    @Transactional
    public CommonResult deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new TenantRole(roleId));
            checkRoleDataScope(roleId);
            TenantRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0){
                return CommonResult.error(role.getRoleName() + "已分配,不能删除");
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        int i = roleMapper.deleteRoleByIds(roleIds);
        if (i > 0) {
            return CommonResult.ok(EmErrorCode.DELETE_OK);
        } else {
            return CommonResult.error(EmErrorCode.DELETE_ERROR);
        }
    }


    /**
    * @Author hbx
    * @Description 通过角色ID查询角色使用数量
    * @Date 2023/6/22 10:19
    * @param roleId
    */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
    * @Author hbx
    * @Description 取消授权用户角色
    * @Date 2023/6/22 10:19
    * @param userRole
    */
    @Override
    public int deleteAuthUser(SysUserRole userRole)
    {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
    * @Author hbx
    * @Description 批量取消授权用户角色
    * @Date 2023/6/22 10:19
    * @param roleId
    * @param userIds
    */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds)
    {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
    * @Author hbx
    * @Description 批量选择授权用户角色
    * @Date 2023/6/22 10:19
    * @param roleId
    * @param userIds
    */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds)
    {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds)
        {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleMapper.batchUserRole(list);
    }
}
